package com.lehecai.core.queue.jms;

import com.lehecai.core.lottery.LotteryType;
import org.apache.commons.lang.StringUtils;

import javax.jms.Queue;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;

/**
 * 创建基于LotteryType的Queue
 * User: sunshow
 */
public class JmsLotteryTypeQueueFactoryBean extends AbstractJmsQueueFactoryBean<LotteryType> {

    private String queueNamePrefix;

    @Override
    protected String generateQueueName(LotteryType lotteryType) {
        return this.generateQueueName(String.valueOf(lotteryType.getValue()));
    }

    protected String generateQueueName(String suffix) {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(this.getQueueNamePrefix())) {
            sb.append(this.getQueueNamePrefix());
        }
        sb.append(suffix);
        return sb.toString();
    }

    public void init(List<LotteryType> lotteryTypeList) {
        List<String> lotteryTypeValueList = new ArrayList<String>();
        for (LotteryType lotteryType : lotteryTypeList) {
            lotteryTypeValueList.add(String.valueOf(lotteryType.getValue()));
        }
        // 填充Map
        Queue queue = this.createQueueByName(this.generateQueueName(StringUtils.join(lotteryTypeValueList, "|")));
        Lock lock = this.getLock();
        lock.lock();
        for (LotteryType lotteryType : lotteryTypeList) {
            this.instanceMap.put(lotteryType, queue);
        }
        lock.unlock();
    }

    public String getQueueNamePrefix() {
        return queueNamePrefix;
    }

    public void setQueueNamePrefix(String queueNamePrefix) {
        this.queueNamePrefix = queueNamePrefix;
    }
}
